package com.xb.sourest.im;

import android.util.Log;

import com.hyphenate.EMContactListener;
import com.xb.sourest.im.event.ComNotifyConfig;
import com.xb.sourest.im.event.ComNotifyEventBean;
import com.xb.sourest.im.event.EventBusHelper;
import com.xb.sourest.storge.db.user.InviteBean;
import com.xb.sourest.storge.db.user.InviteDao;
import com.xb.sourest.storge.db.user.InviteStatus;
import com.xb.sourest.storge.db.user.UserDao;

/**
 * 环信好友事件监听
 */
public class HxContactListener implements EMContactListener {

    private static  final String TAG ="HxContactListener";

    @Override
    public void onContactAdded(String phone) {
        //增加了联系人时回调此方法
        Log.i(TAG,"HxContactListener onContactAdded: phone=" + phone);
    }

    @Override
    public void onContactDeleted(String phone) {
        //被删除时回调此方法
        Log.i(TAG,"HxContactListener onContactDeleted: phone=" + phone);
    }

    @Override
    public void onContactInvited(String phone, String reason) {
        //收到好友邀请
        Log.i(TAG,"HxContactListener onContactInvited: phone=" + phone);
        //存储到数据库中
        InviteBean inviteBean = new InviteBean(phone, System.currentTimeMillis());
        if (InviteDao.getInstance().saveIfNotHandled(inviteBean)) {
            //铃声、震动通知
    //        FCNotifyUtils.getInstance().ringtongAndVibratorNotify();
            //通知相关界面刷新
            EventBusHelper.getInstance().post(new ComNotifyEventBean(ComNotifyConfig.REFRESH_USER_INVITE));
        }
    }

    @Override
    public void onFriendRequestAccepted(String phone) {
        //好友请求被同意
        Log.i(TAG,"HxContactListener onContactAgreed: phone=" + phone);
        InviteBean inviteBean = new InviteBean(phone, System.currentTimeMillis(), InviteStatus.BE_AGREED);
        if (InviteDao.getInstance().save(inviteBean) != -1) {
            //铃声、震动通知
     //       FCNotifyUtils.getInstance().ringtongAndVibratorNotify();
            //通知相关界面刷新
            EventBusHelper.getInstance().post(new ComNotifyEventBean(ComNotifyConfig.REFRESH_USER_INVITE));
            //更新数据库并通知通讯录界面刷新
            addOrUpdateNewUserData(phone);
        }
    }

    @Override
    public void onFriendRequestDeclined(String phone) {
        //好友请求被拒绝
        Log.i(TAG,"HxContactListener onContactRefused: phone=" + phone);
        InviteBean inviteBean = new InviteBean(phone, System.currentTimeMillis(), InviteStatus.BE_REJECTED);
        if (InviteDao.getInstance().save(inviteBean) != -1) {
            //铃声、震动通知
    //        FCNotifyUtils.getInstance().ringtongAndVibratorNotify();
            //通知相关界面刷新
            EventBusHelper.getInstance().post(new ComNotifyEventBean(ComNotifyConfig.REFRESH_USER_INVITE));
        }
    }

    //更新数据库并通知通讯录界面刷新
    private void addOrUpdateNewUserData(String phone) {
        //更新数据库
        UserDao.getInstance().addOrUpdateUser(phone);
        //发送Eventbus通知通讯录刷新
        EventBusHelper.getInstance().post(new ComNotifyEventBean(ComNotifyConfig.REFRESH_CONTACT_IN_DB));
    }
}
